package com.yvon.maple.service.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.google.common.collect.Lists;
import com.yvon.boot.mybatis.BaseServiceImpl;
import com.yvon.maple.service.system.mapper.UserRoleMapper;
import com.yvon.maple.service.system.dto.UserRoleDTO;
import com.yvon.maple.service.system.entity.UserRole;
import com.yvon.maple.service.system.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : Yvon
 * @version : 1.0
 * @since : 2021/3/15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserRoleServiceImpl extends BaseServiceImpl<UserRole, UserRoleMapper> implements UserRoleService {
    @Override
    public boolean save(Long userId, List<Long> roleIds) {
        if (null == roleIds) {
            return false;
        }
        removeByUserIds(Lists.newArrayList(roleIds));
        if (CollUtil.isNotEmpty(roleIds)) {
            List<UserRole> list = new ArrayList<>();
            roleIds.forEach(roleId -> {
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                list.add(userRole);
            });
            return saveBatch(list);
        }
        return true;
    }

    @Override
    public List<Long> getUserIdsByRoleIds(List<Long> roleIds) {
        List<UserRole> list = lambdaQuery()
                .in(UserRole::getRoleId, roleIds)
                .list();
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(UserRole::getUserId).distinct().collect(Collectors.toList());
        }
        return new ArrayList<>();
    }


    @Override
    public boolean removeByUserIds(Collection<Long> userIds) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        return SqlHelper.retBool(baseMapper.delete(queryWrapper));
    }


    @Override
    public List<UserRoleDTO> getByUserId(Long userId) {
        return baseMapper.getByUserIds(Lists.newArrayList(userId));
    }


    @Override
    public Map<Long, List<UserRoleDTO>> getByUserIds(Collection<Long> userIds) {
        if (CollUtil.isNotEmpty(userIds)) {
            List<UserRoleDTO> groupings = baseMapper.getByUserIds(userIds);
            return groupings.stream().collect(Collectors.groupingBy(UserRoleDTO::getUserId));
        }
        return new HashMap<>(1);
    }
}
